package com.dogstudio.popstart.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.LruCache;

import com.dogstudio.popstart.R;
import com.dogstudio.popstart.app.GameApp;
import com.dogstudio.popstart.config.Config;

public class LruLoader {

    private static LruLoader instance;

    private LruCache<String, Bitmap> mCache;

    public static LruLoader get() {
        if (instance == null) {
            instance = new LruLoader();
        }
        return instance;
    }

    private LruLoader() {
        int cacheSize = (int) (Runtime.getRuntime().freeMemory() / 8);
        mCache = new LruCache<String, Bitmap>(cacheSize);
        cacheBitmap(R.drawable.block_select);
    }

    public void cacheBitmap(int id) {
        if (id == 0) {
            return;
        }
        String drawableName = GameApp.getInstance().getResources().getResourceName(id);
        if (mCache.get(drawableName) == null) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            Bitmap bitmap = BitmapFactory.decodeResource(GameApp.getInstance().getResources(), id, options);
            mCache.put(drawableName, bitmap);
        }
    }

    public Bitmap getBitmapByType(int type) {
        int id = Config.map.get(type);
        return getBitmap(id);
    }

    public Bitmap getSelBitmap() {
        return getBitmap(R.drawable.block_select);
    }

    private Bitmap getBitmap(int id) {
        if (id == 0) {
            return null;
        }
        String drawableName = GameApp.getInstance().getResources().getResourceName(id);
        Bitmap bitmap = mCache.get(drawableName);
        if (bitmap != null) {
            return bitmap;
        } else {
            BitmapFactory.Options options = new BitmapFactory.Options();
            bitmap = BitmapFactory.decodeResource(GameApp.getInstance().getResources(), id, options);
            LogUtils.e("w:" + bitmap.getWidth() + ",h:" + bitmap.getHeight());
            mCache.put(drawableName, bitmap);
            return bitmap;
        }
    }

    public void releaseMemory() {
        mCache.evictAll();
    }

}
